#!/bin/bash

# -------------------------------------------------------
DIR="$( cd "$( dirname $0 )" && pwd )"
echo -e  $"Path of script is: \n$DIR"
cd $DIR


# -------------------------------------------------------
CRON_CNT=` ps -ef | grep cron  | grep -v cronjod | grep -v grep | wc -l `
echo "Number of ps that contains cron is: $CRON_CNT "
if [ "$CRON_CNT" -eq "0" ]; then
  echo "WARNING: CRON IS NOT RUNNING! READY TO RESTART..."
  sudo service cron restart
fi



# --------------------------------------------------------
# cronjod
# restart logstash regularly.

CNT=`ps -ef | grep extract.document.DocIncreRun | grep java | wc -l`
echo "NUMBER OF PID is: $CNT"

if [ "$CNT" -eq "0" ]; then 

  echo "DocIncreRun not  RUNNING! Ready to restart!"

  sh extract_doc_incre_run.sh

  #bash -c "nohup sh extract_doc_incre_run.sh >/tmp/temp_output.out 2>/tmp/temp_error.err </dev/null &"

  echo "DOcIncreRun Script Has Been Run! To Check Whether Success, USE: ps -ef | grep DocIncreRun "


else 
  echo "DocIncrerun already Running!"

  #PIDS=`ps -ef | grep logstash | grep java | awk '{print $2}'`
  #for p in $PIDS; do
  #  echo "killing $p"
  #  sudo kill -9 "$p"
  #done

fi



###############
#command in crontab must use absorlute path
###############

if 0; then
  ##########################
  CUR_TIME=`date +%Y-%m-%d.%H:%M:%S`
  LOG_FILE="../logs/document_incre.log.$CUR_TIME"
  echo $LOG_FILE

  CURPATH="$( pwd )"
  echo "CURPATH = $CURPATH"

  CURUSER=`whoami`
  echo "CURUSER = $CURUSER"

  CURENV=`echo $PATH`
  echo "CURENV = $CURENV"

  FILES=`ls`
  echo "FILES = "
  echo $FILES

  JAVA="/usr/java/jdk1.8.0_60/bin/java"

  JAVAV=`$JAVA -version`
  echo "JAVAV = $JAVAV"

  PYTHON="/usr/bin/python"
  PYTHONV=`$PYTHON --version`
  echo "PYTHONV = $PYTHONV"

  #$JAVA -cp media-extraction.jar extract.document.DocIncreRun

  echo "Start DocIncreRun Success!"
  ##########################
fi


# ---------------------------------------------------------
